using System;
using System.ComponentModel;
using System.ComponentModel.Design;

namespace VisualPureBasicIDE.FormDesigner.Implementations
{
    /// <summary>
    /// Summary description for NameCreationServiceImpl.
    /// </summary>
    public class NameCreationService : System.ComponentModel.Design.Serialization.INameCreationService, INameCreationService
    {
        private readonly IDesignerHost _designerHost;

        public NameCreationService(IDesignerHost host)
        {
            if (host == null)
            {
                throw new ArgumentException("_designerHost");
            }
            _designerHost = host;
        }

        #region INameCreationService Members

        /// <summary>
        /// creates a unique name from the given container and dataType
        /// </summary>
        /// <param name="container"></param>
        /// <param name="dataType"></param>
        /// <returns></returns>
        public string CreateName(IContainer container, Type dataType)
        {
            if (container == null)
            {
                throw new ArgumentException("container");
            }
            if (dataType == null)
            {
                throw new ArgumentException("dataType");
            }
            // look to see if the container already has this type
            // of component, if it does, then iterate until you
            // find a unique name
            //const int count = 1;
            var compName = dataType.Name + 1;
            if (container.Components[compName] != null)
            {
                for (var i = 1; i < container.Components.Count; i++)
                {
                    compName = dataType.Name + (i + 1);
                    if (container.Components[compName] == null)
                    {
                        break;
                    }
                }
            }
            return compName;
        }

        public bool IsValidName(string name)
        {
            ValidateName(name);
            return true;
        }

        public void ValidateName(string name)
        {
            // iterate the comps in the component container and 
            // make sure that the name is not used already
            if (_designerHost.Container == null)
            {
                throw new Exception("Null container.");
            }
            // if we have some components
            if (_designerHost.Container.Components != null &&
                _designerHost.Container.Components.Count > 0)
            {
                foreach (IComponent comp in _designerHost.Container.Components)
                {
                    if (string.Compare(name, comp.Site.Name) == 0)
                    {
                        throw new Exception("Name alreay in use.");
                    }
                }
            }
        }

        #endregion
    }
}